# build_and_deploy.ps1

# --- 配置 ---
$REGISTRY = "bbbjkl461"
$BACKEND_IMAGE = "$REGISTRY/django-backend"
$FRONTEND_IMAGE = "$REGISTRY/vue-frontend"

# --- 1. 生成唯一的镜像标签 ---
# 使用 年月日-时分秒 的格式，例如: 20250829-113055
$TAG = (Get-Date -Format "yyyyMMdd-HHmmss")
echo "--- Generated unique tag: $TAG ---"


echo "--- 2. Building Images ---"
docker build -t "$BACKEND_IMAGE`:$TAG" -f backend/Dockerfile backend
docker build -t "$FRONTEND_IMAGE`:$TAG" -f frontend/Dockerfile frontend


echo "--- 3. Pushing Images to Local Registry ---"
docker push "$BACKEND_IMAGE`:$TAG"
docker push "$FRONTEND_IMAGE`:$TAG"


echo "--- 4. Updating Kubernetes Deployment Manifest ---"
# 这是关键步骤：使用新生成的 $TAG 更新 deployment.yml 文件
$deploymentFile = "k8s/deployment.yml"

# 更新 Django backend 的镜像标签
(Get-Content $deploymentFile) -replace "(image: ${REGISTRY}/django-backend):.*", "`$1:$TAG" | Set-Content $deploymentFile
echo "Updated backend image in $deploymentFile to $BACKEND_IMAGE`:$TAG"

# 更新 Vue frontend 的镜像标签
(Get-Content $deploymentFile) -replace "(image: ${REGISTRY}/vue-frontend):.*", "`$1:$TAG" | Set-Content $deploymentFile
echo "Updated frontend image in $deploymentFile to $FRONTEND_IMAGE`:$TAG"


echo "--- 5. Deploying to Kubernetes ---"
# 现在 apply 命令会检测到 deployment.yml 的变化
kubectl apply -f k8s/


echo "--- 6. Verifying Deployment ---"
kubectl get pods
kubectl wait --for=condition=ready pod --selector=app=django-backend --timeout=300s
kubectl exec -it django-backend-deployment-xxx -- sh -c "python manage.py test"

$backendPod = kubectl get pods --selector=app=django-backend -o jsonpath='{.items[0].metadata.name}'
if ($backendPod) {
    echo "Executing tests in Pod: $backendPod"
    kubectl exec -it $backendPod -- sh -c "python manage.py test"
} else {
    echo "Error: No ready django-backend Pod found"
    exit 1
}

echo "--- Deployment finished. It might take a moment for the new pods to be in 'Running' state. ---"